package mallindex

import (
	"context"
	"strconv"

	"mall/common/cachex"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/lib/shoppingcart"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetShoppingCartInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetShoppingCartInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetShoppingCartInfoLogic {
	return &GetShoppingCartInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetShoppingCartInfoLogic) GetShoppingCartInfo(
	req *types.GetShoppingCartInfoReq,
	headers *[]*types.Header,
) (resp *types.ShoppingCartInfo, err error) {
	var qty uint32

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return &types.ShoppingCartInfo{
			Quantity: pointy.GetPointer(qty),
		}, nil
	}

	shoppingCart := shoppingcart.NewShoppingCart(l.ctx, l.svcCtx, cachex.ForumShoppingCart)
	cnt, err := shoppingCart.Count(strconv.FormatInt(int64(userId), 10))
	if err != nil {
		logx.Errorw("GetShoppingCartInfo Count err", logx.Field("detail", err.Error()))
	} else if cnt > 0 {
		qty = uint32(cnt)
	}

	return &types.ShoppingCartInfo{
		Quantity: pointy.GetPointer(qty),
	}, nil
}
